package com.vnetoo.osfilesvr;

import java.io.IOException;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.io.FileSystemUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 * @author chenh
 * 获取磁盘空间
 */
public class DiskSpace extends Thread{
	
	public static final Logger log=Logger.getLogger(ServerThread.class);	
	private int time=5000;	                    //默认心跳
	private boolean interupted=false;			//线程是否被终止
	private JdbcTemplate jt;
	
	public DiskSpace(int time){
		this.time=time;
	}
	
	/**
	 * 睡眠time
	 */
	private void sleepTime(){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {				
			interupted=true;
		}
	}
	
	public void run() {
		jt=getJdbcTemplate();
		while(!interupted)
		{
			diskSpace();			
			sleepTime();
		}
	}
	
	/**
	 * @return JdbcTemplate
	 */
	private JdbcTemplate getJdbcTemplate(){
		ApplicationContext ac= new FileSystemXmlApplicationContext(
				"datasourse.xml");
		BasicDataSource ds=(BasicDataSource)ac.getBean("dataSource");
				
		return new JdbcTemplate(ds);
	}
	
	class PathItem{
		int id;
		String path;
	}
	
	public void diskSpace(){
		
		String sql="select id id,HP_PATH path from STORE_PATH where enabled_flag=1";
		//log.info(sql);
		List list=jt.query(sql, new RowMapper(){
			public Object mapRow(java.sql.ResultSet rs, int i) throws java.sql.SQLException{
				PathItem pathItem=new PathItem();
				pathItem.id=rs.getInt("id");
				pathItem.path=rs.getString("path");
				return pathItem;
			}
		});
		if(list==null||list.isEmpty())
			return;
		for(int i=0;i<list.size();i++){
			PathItem pathItem=(PathItem)list.get(i);
			if(pathItem.path==null||pathItem.path.equals(""))
				continue;
			try {
				double space=FileSystemUtils.freeSpaceKb(pathItem.path)/1024;
				sql="update STORE_PATH set PHYSICAL_SPACE="+space+" where id="+pathItem.id;
				//log.info(sql);
				jt.execute(sql);
			} catch (IOException e) {				
				//e.printStackTrace();
				log.error(e.getMessage());
			}
		}
	}
	
}





